<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    width="50%"
    @close="handleCancel(formRef)"
  >
    <template #title>关联子网</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item field="name" label="当前网络" label-col-flex="70px">
          <p class="text_p">{{ $route.query?.name }}</p>
        </ga-form-item>
        <ga-card
          :style="{ backgroundColor: '#F7F9FC' }"
          title="平台子网"
          :bordered="false"
        >
          <template #extra>
            <ga-link :hoverable="false" @click="() => handleAdd()">
              <template #icon><icon-plus /></template>添加
            </ga-link>
          </template>
          <ga-table
            row-key="id"
            :columns="columns"
            :data="tableData"
            :bordered="false"
            size="medium"
            :hoverable="false"
            :pagination="false"
            :scroll="{ y: 220 }"
          >
            <template #resourceId="{ record, rowIndex }">
              <ga-select
                size="small"
                v-model="record.resourceId"
                @change="handleChangePlatform(record, rowIndex)"
                placeholder="请选择平台"
              >
                <ga-option
                  v-for="item in platformTreeList"
                  :key="item.value"
                  :value="item.tableId"
                >
                  {{ item.name }}
                </ga-option>
              </ga-select>
            </template>
            <template #clusterUuid="{ record, rowIndex }">
              <ga-select
                placeholder="请选择集群"
                size="small"
                v-model="record.clusterUuid"
                @change="handleChangeCluster(record, rowIndex)"
              >
                <ga-option
                  v-for="item in clusterList"
                  :key="item.value"
                  :value="item.clusterUuid"
                >
                  {{ item.name }}
                </ga-option>
              </ga-select>
            </template>
            <template #networkSubnetUuid="{ record }">
              <ga-select
                :disabled="!(record.resourceId && record.clusterUuid)"
                v-model="record.networkSubnetUuid"
                multiple
                size="small"
                allow-clear
                :max-tag-count="1"
                placeholder="请选择子网"
              >
                <ga-option v-for="item in subnetList" :key="item.id" :value="item.uuid">
                  {{ item.name }}
                </ga-option>
              </ga-select>
            </template>
            <template #action="{ rowIndex }">
              <ga-link
                status="danger"
                :hoverable="false"
                @click="() => tableData.splice(rowIndex, 1)"
              >
                移除
              </ga-link>
            </template>
          </ga-table>
        </ga-card>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, reactive } from "vue";
import { createIp } from "@/api/layer2subnet.ts";
import { getPlatformTreeList, getNetworkList } from "@/api/network.ts";
import { Message } from "@garco-design/web-vue";
import useLoading from "@/hooks/loading";
import { useRoute } from "vue-router";

const route = useRoute();
const { id } = route.params;
const { loading, setLoading } = useLoading(false);
const formRef = ref(null);
const tableData = ref([]);
const platformTreeList = ref([]);
const clusterList = ref([]);
const subnetList = ref([]);
const formData = ref([]);
const visible = ref(false);
const columns = [
  {
    title: "平台",
    dataIndex: "resourceId",
    slotName: "resourceId",
  },
  {
    title: "集群",
    dataIndex: "clusterUuid",
    slotName: "clusterUuid",
  },
  {
    title: "子网",
    dataIndex: "networkSubnetUuid",
    slotName: "networkSubnetUuid",
    width: 300,
  },
  {
    title: "操作",
    width: 60,
    slotName: "action",
  },
];
const resolveOption = (data) => {
  return data?.filter(
    (item) =>
      !tableData.value.some((c) => c.networkSubnetUuid?.includes(item.networkUuid))
  );
};
// 处理方法
const handleAdd = () => {
  tableData.value.push({
    resourceId: "",
    clusterUuid: "",
    networkSubnetUuid: [],
  });
};
// 处理改变平台方法
const handleChangePlatform = ({ resourceId, clusterUuid }, rowIndex) => {
  clusterList.value = [];
  console.log("resourceId", resourceId);
  // smartx 必须选择平台和集群
  tableData.value[rowIndex].clusterUuid = "";
  tableData.value[rowIndex].networkSubnetUuid = [];
  clusterList.value =
    platformTreeList.value?.find((item) => item.tableId === resourceId)?.children || [];
  fetchSubnetData(resourceId);
};
// 处理改变集群方法
const handleChangeCluster = ({ resourceId, clusterUuid }, rowIndex) => {
  subnetList.value = [];
  tableData.value[rowIndex].networkSubnetUuid = [];
  fetchSubnetData(resourceId, clusterUuid);
};
// 获取平台tree列表
const fetchPlatformTreeData = async () => {
  try {
    const { data } = await getPlatformTreeList({ limit: -1 });
    platformTreeList.value = data || [];
  } finally {
    setLoading(false);
  }
};
// 获取子网列表
const fetchSubnetData = async (resourceId, clusterUuid) => {
  try {
    const { data } = await getNetworkList({
      limit: -1,
      resourceId,
      clusterUuid,
      filterProject: 1,
      subnetId: id,
    });
    subnetList.value = resolveOption(data?.items);
    // subnetList.value = data?.items || [];
  } finally {
    setLoading(false);
  }
};

const open = async () => {
  setLoading(true);
  visible.value = true;
  fetchPlatformTreeData();
};
// 保存
const emits = defineEmits(["fetchData"]);
const transformData = (data) => {
  const result = [];
  data.forEach((item) => {
    item.networkSubnetUuid.forEach((subnetUuid) => {
      result.push({
        resourceId: item.resourceId,
        clusterUuid: item.clusterUuid,
        networkSubnetUuid: subnetUuid,
      });
    });
  });
  return result;
};

// 判断函数
const checkAllItemsNotEmpty = (data) => {
  for (const item of data) {
    // 检查 resourceId 是否为空
    if (!item.resourceId) {
      return false;
    }
    // 检查 clusterUuid 是否为空
    if (!item.clusterUuid) {
      return false;
    }
    // 检查 networkSubnetUuid 是否为空数组
    if (!Array.isArray(item.networkSubnetUuid) || item.networkSubnetUuid.length === 0) {
      return false;
    }
  }
  return true;
};

const handleOk = async () => {
  if (tableData.value?.length > 0 && checkAllItemsNotEmpty(tableData.value)) {
    formData.value = transformData(tableData.value);
    try {
      const { code } = await createIp(id, "network", formData.value);
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
    } finally {
      visible.value = false;
    }
  } else {
    Message.warning("请选择要关联的信息");
  }
};
const handleCancel = (formEl) => {
  formEl.resetFields();
  subnetList.value = [];
  formData.value = [];
  platformTreeList.value = [];
  clusterList.value = [];
  tableData.value = [];
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
